package assignment1;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.Set;

/**
 * 
 * @author Kha Nguyen - 598240
 *
 */
public class ReadInputFileTask implements Runnable {

    private static final String ALPHA_NUM_CHARS = "^[a-zA-Z0-9]+$";

    private static final String NON_ALPHA_NUM_CHARS = "[^a-zA-Z0-9]";

    private final String fileName;

    private final Set<String> tokenContainer;

    public ReadInputFileTask(String fileName, Set<String> tokenContainer) {
        super();
        this.fileName = fileName;
        this.tokenContainer = tokenContainer;
    }

    @Override
    public void run() {
        Scanner reader = null;
        try {
            final File fileToProcess = new File(fileName);
            reader = new Scanner(fileToProcess);

            while (reader.hasNextLine()) {
                final String[] processedTokens = reader.nextLine().toLowerCase().split(NON_ALPHA_NUM_CHARS);
                for (String token : processedTokens) {
                    if (token.isEmpty()) {
                        continue;
                    }

                    if (!token.matches(ALPHA_NUM_CHARS)) {
                        throw new RuntimeException(token);
                    }

                    tokenContainer.add(token);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
}
